package com.sun.nacos.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 基于集群的负载均衡
 */
@Slf4j
public class NacosClusterRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    @Override
    public Server choose(Object o) {
        // 获取集群名称
        String clusterName = nacosDiscoveryProperties.getClusterName();
        // 获取服务的名称
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
        // 想要请求的微服务
        String serverName = loadBalancer.getName();
        // 服务发现相关API
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

        try {
            // 找到指定服务的所有实例
            List<Instance> instances = namingService.selectInstances(serverName, true);
            // 过滤出相同集群下的所有实例
            List<Instance> sameClusterInstance = instances.stream()
                    .filter(instance -> Objects.equals(instance.getClusterName(), clusterName))
                    .collect(Collectors.toList());
            // 如果集群中没有实例选择其他集群实例
            List<Instance> chooseInstance = new ArrayList<>();
            if(CollectionUtils.isEmpty(sameClusterInstance)) {
                chooseInstance = instances;
            } else {
                chooseInstance = sameClusterInstance;
            }
            // 基于权重的负载均衡算法
            Instance instance = ExtendBalancer.getHostByRandomWeightSelf(chooseInstance);
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error("发生异常", e);
        }
        return null;
    }
}

class ExtendBalancer extends Balancer {
    public static Instance getHostByRandomWeightSelf(List<Instance> hosts) {
        return getHostByRandomWeight(hosts);
    }
}